﻿using System;
using System.Web;
using Dynamicweb.eCommerce.Orders;
using Dynamicweb.Extensibility;

namespace Webshop.CustomModules.Extentions
{
	public class OrderTemplateExtender1 : OrderTemplateExtender
	{
		
		private Dynamicweb.Templatev2.Template _template;

		public override void ExtendTemplate(Dynamicweb.Templatev2.Template Template, Dynamicweb.eCommerce.Frontend.TemplateExtenderRenderingState RenderingState)
		{
			if ( DwProjectTemplate.App.CodeSettings.EnableOrderTemplateExtender1 )
			{
				// Make the template global inside the class
				_template = Template;

				/* Here you have a Hashtable with a lot of page properties (ex. ht["pagetitle"] is the 
				 * value of the title tag inside the head
				 */
				// Hashtable ht = Dynamicweb.Frontend.PageView.Current().Page.Values;

				if ( RenderingState == Dynamicweb.eCommerce.Frontend.TemplateExtenderRenderingState.Before )
				{
					/* Run your extension inside here this to leave the possibility to overwrite 
					 * any standard Dynamicweb template tags
					 */

					/* Use with care since changing the currency on the order with existing orderlines can trigger 
					 * "Arithmetic exception with different currencies" 
					 */

					// SetOrderCurrency();

					// Validates that the amount on an OrderLine in the basket is validated against the Stock on the product
					StockOrderlineAmountValidation();

				}
				else if ( RenderingState == Dynamicweb.eCommerce.Frontend.TemplateExtenderRenderingState.After )
				{
					// Use with care because you can overwrite standard Dynamicweb template tags
				}

				/* When we do modifications to the Order - we need to re-calculate it, because DW already has 
				 * done their logic. (BUG?)
				 */
				CalculateOrderPrice();
			}
		}

		private void CalculateOrderPrice()
		{
			base.Order.Price.PriceWithVAT = base.Order.PriceBeforeFees.Price + base.Order.ShippingFee.PriceWithVAT;
		}

		private void StockOrderlineAmountValidation()
		{
			/* Make sure you only do the stock validation and your last cart-accept-step before payment.
			 * This default runs in all cart-views you have!!!
			 */

			bool isStepX = true; // HttpContext.Current.Request[ "CartV2.GotoStep2" ] != null;
			Dynamicweb.Templatev2.Template soldOutLoop = _template.GetLoop("BestPractices.OrderLines.SoldOut");
			foreach (OrderLine ol in base.Order.OrderLines)
			{
				double stock = ol.Product.Stock;
				double amount = ol.Quantity;

				if (amount > stock && isStepX)
				{
					soldOutLoop.SetTag( "BestPractices.OrderLine.ID", ol.ID );
					soldOutLoop.SetTag( "BestPractices.OrderLine.IsSoldOut", "true" );
					soldOutLoop.CommitLoop();
					ol.Quantity = stock;
					ol.Save();

					base.Order.Save();
				}
			}
		}

		private void SetOrderCurrency(string currencyCode, int paymentGatewayCurrencyCode, string currencySymbol)
		{
			Dynamicweb.eCommerce.International.Currency c = Dynamicweb.eCommerce.Common.Context.Currency;
			c.Code = currencyCode;
			c.PayGatewayCode = paymentGatewayCurrencyCode;
			c.Symbol = currencySymbol;
			Dynamicweb.eCommerce.Common.Context.Currency = c;
			Dynamicweb.eCommerce.Common.Context.CurrencySetByCustomer = true;
		}
	}

}